<?php

namespace app\index\controller;

use app\common\model\AuthGroupAccess;
use app\common\model\AuthGroup;
use app\common\model\Admin;
use think\Session;

/**
 * 工地主管理
 *
 * @icon fa fa-circle-o
 */
class Site extends User
{
    
    /**
     * Site模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Site');
        $this->view->assign("buildingCustomerTypeList", $this->model->getBuildingCustomerTypeList());
        $this->view->assign("buildingStatusList", $this->model->getBuildingStatusList());
        $this->view->assign("buildingIsEncoreList", $this->model->getBuildingIsEncoreList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function site_list()
    {  
        $params = $this->request->param(); 
        $building_name = '';
        $this->view->assign("building_status",!empty($params['building_status'])?$params['building_status']:'');
        //设置过滤方法 
        $where= array(); 
            // list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        if(array_key_exists('building_status',$params)){
            $where['building_status'] = $params['building_status'];  
        }
         if(array_key_exists('building_name',$params)){
            $building_name = $params['building_name'];
            $where['building_name'] = array('LIKE',"%$building_name%");  
        }
        $this->view->assign("building_name",$building_name);
        $offset = 0;
        $limit = 100;
        $total = $this->model
                ->where(["building_delete"=>0])
                ->where($where) 
                ->count();

        $list = $this->model
                ->where(["building_delete"=>0])
                ->where($where) 
                ->limit($offset, $limit)
                ->select();

        $list = collection($list)->toArray();
        $result = array("total" => $total, "rows" => $list);

        if ($this->request->isAjax())
        {
            return json($result);
        }else{
            $this->view->assign("result",$result);
        }
        return $this->view->fetch();
    }
    public function add_person($id = 4){
        $list = array();
        $where = array();
        if ($this->request->isPost())
        {
            $username = $this->request->post("username");  
            $GroupIds = Admin::where(['username'=>array('LIKE',"%$username%")])->select();
            if(!empty($GroupIds)){ 
                foreach ($GroupIds as $key => $value) {
                    $ids[] = $value->id;
                }
                $where['uid'] = array('in',$ids);  
            }  
        }
        $authGroupList = AuthGroupAccess::where('group_id',$id)->where($where)
                    ->field('uid,group_id')
                    ->select();
        if($authGroupList){ 
            foreach ($authGroupList as $key => $value) {
                $childrenGroupIds[]=$value['uid'];
            } 
            $list = Admin::where('id', 'in', $childrenGroupIds)
                        ->column('id,username,avatar');
        }
        $this->view->assign("list",$list);
        return $this->view->fetch();
    }
    //选择资产
    public function add_property(){
        $params = $this->request->param();
        $where = $property_small_category_list =  array(); 
        $where['property_status'] = 4;
        if(!empty($params['property_large_category'])){ 
            $this->view->assign("property_small_category_list", $property_small_category_list);   
            $property_small_category_list = $this->getDictionary($params['property_large_category']);
        }

        $this->view->assign("property_small_category_list", $property_small_category_list);  

        if(!empty($params['property_small_category']))
            $where['property_small_category'] = $params['property_small_category'];

        if(!empty($params['property_warehouse']))
            $where['property_warehouse'] = $params['property_warehouse'];
        $sort = 'id';
        $order = 'desc';
        $offset = 0;
        $limit = 100;
        $list = model('Property')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

        $list = collection($list)->toArray();
        $this->view->assign("params",$params);  
        $this->view->assign("list",$list);  
        $this->view->assign("property_large_category", $this->getDictionary('30000'));  
        $this->view->assign("property_warehouse", $this->getDictionary('40000'));   
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function site_add()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                 
                try
                {     
                    //添加额外参数
                    $params["building_add_user_id"] = $this->auth->id;
                    $params["building_add_user_name"] = $this->auth->username;
                    $params["building_create_time"] = time();
                    $params["building_project_address"] = $params["building_project_address"].$params["address"];
                    $params["building_status"] = 1;

                    $result = $this->model->allowField(true)->save($params);
                    $insert_id = $this->model->getLastInsID();
                    
                    //班主数据
                    $bzarr = explode(',', $params["bzstr"]);

                    if(!empty($bzarr)){
                        foreach ($bzarr as $value) {
                            $this->add_site_managers($insert_id,$value,4);
                        }
                    }
                    //施工员
                    $sgystr = explode(',', $params["sgystr"]);
                    if(!empty($sgystr)){
                        foreach ($sgystr as $value) {
                            $this->add_site_managers($insert_id,$value,5);
                        }
                    }
                    //施工工人
                    $sggrstr = explode(',', $params["sggrstr"]);
                    if(!empty($sggrstr)){
                        foreach ($sggrstr as $value) {
                            $this->add_site_managers($insert_id,$value,6);
                        }
                    }


                    //资产使用记录
                    $propertystr = $this->request->post("propertystr");
                    $propertyarr = explode(',', $propertystr);
                    if(!empty($propertyarr)){
                        foreach ($propertyarr as $key => $value) {
                            $dd['property_name'] = substr($propertyarr[$key],strrpos($propertyarr[$key],'^')+1);   
                            $dd['property_id']  = substr($propertyarr[$key],0,strrpos($propertyarr[$key],'^'));
                            $dd['site_id'] = $insert_id;
                            $dd['site_name'] = $params["building_name"];
                            $dd['property_use_time'] = strtotime($params["building_begin_time"]);
                            $dd['create_time'] = time();
                            $dd['user_id'] = $this->auth->id;
                            $dd['user_name'] = $this->auth->username;
                            model('Property')->where('id', $dd['property_id'])->update(['property_status' => '1']); 
                            model('PropertyUse')->insert($dd);
                        } 
                    }

                    // var_dump($this->model_insert_id); 
                    if ($result !== false)
                    {
                        $this->success('新增工地成功',url('user/index'));
                    }
                    else
                    {
                        $this->error($this->model->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    //上传图片
    public function uploadpic(){ 
        $filename = uniqid().'.jpg';  
        //获取base64位图片流  解析出二进制图片数据
        $img = explode(',',$this->request->post("base64")); 
        $path = "./uploads/".$filename;
        file_put_contents($path, base64_decode($img[1]));  
        $data['code'] = 0;
        $data['data'] = $path;
        echo json_encode($data);
        return; 
    }
    public function add_site_managers($site_id,$username,$identity){
        $data = array();
        $data['site_id'] = $site_id; 
        $user = model('User')->where('username','LIKE',"%$username%")->find()->toArray();   
        $data['managers_user_id'] = $user['id'];
        $data['managers_user_name'] = $username;
        $data['managers_identity'] = $identity;
        $data['create_user_id'] = $this->auth->id;
        $data['create_user_name'] = $this->auth->username;
        $data['create_time'] = time();
        model('Managers')->insert($data);
    }
    public function site_detail($id){ 
        $this->view->assign("son", 1);  
        $row = $this->model->get($id)->toArray();
        $this->view->assign("result", $row);  
        return $this->view->fetch();
    }
    public function site_user($id){ 
        $this->view->assign("son", 2);   
        $row = $this->model->get($id)->toArray();
        $this->view->assign("result", $row);  
 
        $this->view->assign("bzlist", $this->get_managers($id,4)); 
        $this->view->assign("sgylist", $this->get_managers($id,5)); 
        $this->view->assign("sggrlist", $this->get_managers($id,6));   
        
        return $this->view->fetch();
    }
    //获取工地管理者信息
    public function get_managers($id,$identity){
        $t = array();
        $result = model('Managers')->where(['site_id'=>$id,'managers_identity'=>$identity])->select();
        if(!empty($result)){
            foreach ($result as $key => $value) {
               $t[$key]['id'] = $value['managers_user_id'];
               $t[$key]['username'] = $value['managers_user_name'];
            } 
        }
        return $t;
    }
    public function site_assets($id){ 
        $this->view->assign("son", 3);   
        $row = $this->model->get($id)->toArray();
        $this->view->assign("result", $row);  
        $dt = array();
        $PropertyUse = model('PropertyUse')->where('site_id',$id)->select();
        if(!empty($PropertyUse)){
            foreach ($PropertyUse as $key => $value) { 
                $dd[] = $value['property_id'];
            } 
            $Property = collection(model('Property')->where('id','in',$dd)->select())->toArray();
            foreach ($Property as $key => $value) {  
                $dt[$value['property_large_category']]['data'][] = $value; 
            }
        } 
        $this->view->assign("PropertyUse", $dt);   
        return $this->view->fetch();
    }
    public function site_schedule($id){ 
        $this->view->assign("son", 4);   
        $row = $this->model->get($id)->toArray();
        $this->view->assign("result", $row);  
        $where['site_id'] = $id;
        $sort = 'id';
        $order = 'desc';
        $offset = 0;
        $limit = 100;
        $total = model('progress')
                ->where($where) 
                ->count();

        $list = model('progress')
                ->where($where) 
                ->select(); 
        $list = collection($list)->toArray(); 
        $this->view->assign("list", $list);  
        return $this->view->fetch();
    }
    public function site_log($id){ 
        $this->view->assign("son", 5);   
        $row = $this->model->get($id)->toArray();
        $this->view->assign("result", $row); 
        $startTime= ''; 
        $endTime= '';
        $where = "site_id = ".$id;
        $params = $this->request->param(); 
        if(array_key_exists('startTime',$params)){
            $where .= " and log_time between '".strtotime($params['startTime']." 00:00:00")."' and '".strtotime($params['endTime']." 23:59:59")."' ";
            $startTime = $params['startTime'];
            $endTime = $params['endTime'];
        }
        $this->view->assign("startTime", $startTime); 
        $this->view->assign("endTime", $endTime); 
        $sort = 'id';
        $order = 'desc';
        $offset = 0;
        $limit = 100;
        $total = model('log')
                ->where($where)
                ->order($sort, $order)
                ->count();

        $list = model('log')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

        $list = collection($list)->toArray();
        $t = array();
        foreach ($list as $v) {
            $dt = date('Y-m-d',$v['log_time']);
            $t[$dt]['data'][] = $v; 
        }
        $this->view->assign("dd", $t);  
        return $this->view->fetch();
    }
    public function site_finance($id){ 
        $this->view->assign("son", 6);   
        $row = $this->model->get($id)->toArray();
        $this->view->assign("result", $row); 

        $where['site_id'] = $id; 
        // list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $sort = 'id';
        $order = 'desc';
        $offset = 0;
        $limit = 100;
        $total = model('Finance')
                ->where($where)
                ->order($sort, $order)
                ->count();

        $list = model('Finance')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

        $list = collection($list)->toArray();
        $result = array("total" => $total, "rows" => $list);
        $this->view->assign("list", $result);  

        $this->view->assign("zcsum", model('Finance')->where($where)->where(['apply_type'=>2])->sum('amount')); 
        $this->view->assign("srsum", model('Finance')->where($where)->where(['apply_type'=>1])->sum('amount')); 
         
        return $this->view->fetch();
    }
    //
    public function site_signature($id){ 
        $this->view->assign("son", 7);   
        $row = $this->model->get($id)->toArray();
        $this->view->assign("result", $row);  
        return $this->view->fetch();
    } 
    //进度列表
    public function schedule_list(){
        $params = $this->request->param(); 
        $site_id = empty($params['site_id'])?1:$params['site_id'];
        $progress_status = array_key_exists('progress_status',$params)?$params['progress_status']:'';
        $building = $this->model->where('id',$site_id)->find()->toArray();
        $this->view->assign("building_name", $building['building_name']);
        $where['site_id'] = $site_id;
          
        if($progress_status||$progress_status==='0'){ 
            $where['progress_status'] = $progress_status;
        }
        // list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $sort = 'id';
        $order = 'desc';
        $offset = 0;
        $limit = 100;
        $total = model('progress')
                ->where($where)
                ->order($sort, $order)
                ->count();

        $list = model('progress')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

        $list = collection($list)->toArray();
        $result = array("total" => $total, "rows" => $list);
        $this->view->assign("result", $result);  
        $this->view->assign("site_id", $site_id); 
        $this->view->assign("progress_status", $progress_status); 


        $list = model('Site')->where(["building_delete"=>0])->select(); 
        if($list){ 
            foreach ($list as $key => $value) {
                $siteList[$key]['value'] = $value['id']; 
                $siteList[$key]['text'] = $value['building_name'];
            } 
            $this->view->assign("siteList",json_encode($siteList));
        }else{
            $this->error('暂无工地数据');
        }

        return $this->view->fetch();
    }
    //新增进度
    public function schedule_add(){
        if ($this->request->isPost())
        {
            $params = $this->request->post();
            if(model('progress')->where(['progress_status'=>1,'site_id'=>$params['site_id']])->find())
                $this->error('该工地已提交结算单，无法新增进度');
            try {
                $params['user_id'] = $this->auth->id;
                $params['user_name'] = $this->auth->username;
                $params['progress_add_time'] = time();
                // $site_name =  model('Site')->where(["id"=>$params['site_id']])->find()->toArray();
                // $params['site_name'] = $site_name['building_name'];
                $result = model('progress')->save($params);
                if ($result !== false)
                {
                    $this->success();
                }
                else
                {
                    $this->error($this->model->getError());
                }
            } catch (Exception $e) {
                $this->error($e->getMessage());
            } 
        }
        $list = model('Site')->where(["building_delete"=>0])->select(); 
        if($list){ 
            foreach ($list as $key => $value) {
                $siteList[$key]['value'] = $value['id']; 
                $siteList[$key]['text'] = $value['building_name'];
            } 
            $this->view->assign("siteList",json_encode($siteList));
        }else{
            $this->error('暂无工地数据');
        }
        return $this->view->fetch();
    }
    public function schedule_detail($id){
        $row = model('progress')->get($id)->toArray();
        $this->view->assign("result", $row);  
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            if (!in_array($row[$this->dataLimitField], $adminIds))
            {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }

                    //添加额外参数
                    $params["last_update_user_id"] = Session::get("admin.id");
                    $params["last_update_user_name"] = Session::get("admin.username");
                    $params["last_update_time"] = time();

                    $result = $row->allowField(true)->save($params);
                    if ($result !== false)
                    {
                        $this->success();
                    }
                    else
                    {
                        $this->error($row->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids)
        {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds))
            {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v)
            {
                $v->allowField(true)->save(["building_delete"=>1]);
                $count++;
//                $count += $v->delete();
            }
            if ($count)
            {
                $this->success();
            }
            else
            {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
